import React, {
    useState,
    useEffect,
    useLayoutEffect
} from "react"
import { Select, Drawer, Upload, Radio, DatePicker, message } from "antd"
import { Empty, Loading } from "../../component/common"
import zhCN from "antd/es/locale/zh_CN"
import Search from "../component/search"
import TableList from "../component/fileList"
import moment from "moment"
// import domtoimage from "dom-to-image";
import Modal from "../component/modal"
import InfoOption from "../component/infoOption"
import BtnAlert from "../component/btnAlert"
import Scrollbars from "react-custom-scrollbars"
import fetch from "../../util/fetch"
import $ from "jquery"
import "./addModal.scss"

import { getQueryVariable, constructionDate, getDateGap, getRuleTime, getRangeDate } from "../../util/public"
const { Option } = Select
const weekTextInfo = {
    "1": "星期一",
    "2": "星期二",
    "3": "星期三",
    "4": "星期四",
    "5": "星期五",
    "6": "星期六",
    "7": "星期天",
    "0": "星期天",
}
function AddModal (props) {
    let {
        editInfo,
        visible,
        dayInfo,
        changeAddModal,
        kindList,
        termList,
        currentTerm,
        getList,
        currentTermInfo,
        getTermWeekList,
        changeKindModal
    } = props
    const [addInfo, setAddInfo] = useState({})
    const [weekList, setWeekList] = useState([])
    const [dayList, setDayList] = useState([])
    const [editDrawerVisible, setEditDrawerVisible] = useState(false)
    const [editDrawerInfo, setEditDrawerInfo] = useState({})
    const addMethod = () => {
        if (addInfo.weekId) {
            editMethod()
            return
        }
        if (!addInfo.weekName) {
            message.warn("值周名称不能为空")
            return
        }
        if (!addInfo.range) {
            message.warn("日期范围不能为空")
            return
        }
        if (!addInfo.weekGroupInfo && !addInfo.weekGroupId) {
            message.warn("值周组长不能为空")
            return
        }
        if (!addInfo.weekGroupPhone) {
            message.warn("联系方式不能为空")
            return
        }
        if (!/^[0-9|\-|/]*$/g.test(addInfo.weekGroupPhone)) {
            message.warn(`联系方式格式不正确，应由数字、 -、 /组成`)
            return
        }
        if (!weekList.length) {
            message.warn("值周类型不能为空")
            return
        }
        let weekGroupInfo = addInfo.weekGroupInfo ? addInfo.weekGroupInfo : {
            UserName: addInfo.weekGroupName,
            UserID: addInfo.weekGroupId,
            PhotoPath: addInfo.headshot
        }
        let termInfo = {}
        termList.forEach((item) => {
            if (item.termInfo === currentTerm) {
                termInfo = item
            }
        })
        let updateWeekList = [], updateDayList = []
        weekList.forEach((item) => {
            updateWeekList.push({
                weekTypeId: item.weekTypeId,
                teacherId: item.teacherId,
                teacherName: item.teacherName,
                teacherPhone: item.teacherPhone,
                headshot: item.headshot
            })
        })
        dayList.forEach((item) => {
            updateDayList.push({
                dayTime: item.dayTime,
                weekDay: item.weekDay,
                teacherId: item.teacherId,
                teacherName: item.teacherName,
                teacherPhone: item.teacherPhone,
                headshot: item.headshot
            })
        })
        let url = window.BasicProxy + `/api/dutyWeek/create/dutyWeek`
        fetch
            .post({
                url, body: {
                    schoolTermStart: termInfo.startDate.substr(0, 10),
                    schoolTermEnd: termInfo.endDate.substr(0, 10),
                    schoolTermInfo: termInfo.termInfo,
                    schoolId: sessionStorage.getItem("schoolId"),
                    week: 1,
                    weekName: addInfo.weekName,
                    weekStartTime: addInfo.range[0],
                    weekEndTime: addInfo.range[1],
                    weekGroupId: weekGroupInfo.UserID || weekGroupInfo.userId,
                    weekGroupName: weekGroupInfo.UserName || weekGroupInfo.userName,
                    weekGroupPhone: addInfo.weekGroupPhone,
                    headshot: weekGroupInfo.PhotoPath || weekGroupInfo.photoPath,
                    dutyWeekTeacherList: updateWeekList,
                    dutyDayTeacherList: updateDayList
                }
            })
            .then((res) => res.json())
            .then((res) => {
                if (res.code == 200) {
                    message.success("添加成功")
                    changeDrawer(false)
                    changeAddModal(false)
                    getTermWeekList()
                    getList()
                }
            })
    }
    const editMethod = () => {
        if (!addInfo.weekName) {
            message.warn("值周名称不能为空")
            return
        }
        if (!addInfo.range) {
            message.warn("日期范围不能为空")
            return
        }
        if (!addInfo.weekGroupInfo && !addInfo.weekGroupId) {
            message.warn("值周组长不能为空")
            return
        }
        if (!addInfo.weekGroupPhone) {
            message.warn("联系方式不能为空")
            return
        }
        if (!/^[0-9|\-|/]*$/g.test(addInfo.weekGroupPhone)) {
            message.warn(`联系方式格式不正确，应由数字、 -、 /组成`)
            return
        }
        if (!weekList.length) {
            message.warn("值周类型不能为空")
            return
        }
        let weekGroupInfo = addInfo.weekGroupInfo ? addInfo.weekGroupInfo : {
            UserName: addInfo.weekGroupName,
            UserID: addInfo.weekGroupId,
            PhotoPath: addInfo.headshot
        }
        let termInfo = {}
        termList.forEach((item) => {
            if (item.termInfo === currentTerm) {
                termInfo = item
            }
        })
        let updateWeekList = [], updateDayList = []
        weekList.forEach((item) => {
            updateWeekList.push({
                id: item.id,
                weekTypeId: item.weekTypeId,
                teacherId: item.teacherId,
                teacherName: item.teacherName,
                teacherPhone: item.teacherPhone,
                headshot: item.headshot
            })
        })
        dayList.forEach((item) => {
            updateDayList.push({
                id: item.id,
                dayTime: item.dayTime,
                weekDay: item.weekDay,
                teacherId: item.teacherId,
                teacherName: item.teacherName,
                teacherPhone: item.teacherPhone,
                headshot: item.headshot
            })
        })
        let url = window.BasicProxy + `/api/dutyWeek/manage/update`
        fetch
            .put({
                url, body: {
                    schoolTermStart: termInfo.startDate.substr(0, 10),
                    schoolTermEnd: termInfo.endDate.substr(0, 10),
                    schoolTermInfo: termInfo.termInfo,
                    schoolId: sessionStorage.getItem("schoolId"),
                    weekId: addInfo.weekId,
                    week: 1,
                    weekName: addInfo.weekName,
                    weekStartTime: addInfo.range[0],
                    weekEndTime: addInfo.range[1],
                    weekGroupId: weekGroupInfo.UserID || weekGroupInfo.userId,
                    weekGroupName: weekGroupInfo.UserName || weekGroupInfo.userName,
                    weekGroupPhone: addInfo.weekGroupPhone,
                    headshot: weekGroupInfo.PhotoPath,
                    dutyWeekTeacherList: updateWeekList,
                    dutyDayTeacherList: updateDayList
                }
            })
            .then((res) => res.json())
            .then((res) => {
                if (res.code == 200) {
                    message.success("编辑成功")
                    changeDrawer(false)
                    changeAddModal(false)
                    getList()
                }
            })
    }
    const editAddInfo = (key, value) => {
        let info = JSON.parse(JSON.stringify(addInfo))
        if (key === "range") {
            if (getDateGap(value[0], value[1]) >= 20 * 24) {
                message.warn("日期范围不能超过30天，请重新选择")
                return
            }
            let arr = getRangeDate(value)
            let updateArr = [], updateArr2 = []
            arr.forEach((item) => {
                updateArr.push({
                    dayTime: item,
                    weekDay: new Date(item).getDay(),
                    week: weekTextInfo[new Date(item).getDay()]
                })
            })
            updateArr.forEach((item) => {
                let obj = {   //默认值日老师安排
                    ...item
                }
                //先将默认值日设置的老师填充
                dayInfo.forEach((child) => {
                    if (item.weekDay == child.weekDay ||
                        (item.weekDay == 0 && child.weekDay == 7)) {
                        if (child.teacherId) {  //有才赋值，没有继续用默认设置
                            obj.teacherId = child.teacherId
                            obj.teacherName = child.teacherName
                            obj.teacherPhone = child.teacherPhone
                            obj.headshot = child.headshot
                        }
                        if (item.dayTime === child.dayTime) {
                            obj.id = child.id
                        }
                    }
                })
                //再将后来用户编辑的老师信息赋值
                dayList.forEach((child) => {
                    if (item.weekDay == child.weekDay ||
                        (item.weekDay == 0 && child.weekDay == 7)) {
                        if (child.teacherId) {  //有才赋值，没有继续用默认设置
                            obj.teacherId = child.teacherId
                            obj.teacherName = child.teacherName
                            obj.teacherPhone = child.teacherPhone
                            obj.headshot = child.headshot
                        }
                        if (item.dayTime === child.dayTime) {
                            obj.id = child.id
                        }
                    }
                })
                updateArr2.push(obj)
            })
            // console.log(arr, dayList, updateArr, updateArr2);
            setDayList(updateArr2)
        }
        if (key === "weekGroupInfo") {
            let url = window.BasicProxy + `/api/common/user/contact/information`
            fetch
                .get({
                    url, params: {
                        userId: value.userId || value.UserID
                    }
                })
                .then((res) => res.json())
                .then((res) => {
                    if (res.code == 200) {
                        let data = res.data
                        let tel = !Array.isArray(data) ? data ? data.telephone || data.telephone2 : "" : data[0] ? data[0].telephone || data[0].telephone2 : ""
                        info[key] = value
                        info["weekGroupPhone"] = tel
                        setAddInfo(info)
                    }
                })
            return
        }
        if (key === "teacherInfo") {
            let url = window.BasicProxy + `/api/common/user/contact/information`
            fetch
                .get({
                    url, params: {
                        userId: value.userId || value.UserID
                    }
                })
                .then((res) => res.json())
                .then((res) => {
                    if (res.code == 200) {
                        let data = res.data
                        let tel = !Array.isArray(data) ? data ? data.telephone || data.telephone2 : "" : data[0] ? data[0].telephone || data[0].telephone2 : ""
                        info[key] = value
                        info["teacherPhone"] = tel
                        setAddInfo(info)
                    }
                })
            return
        }
        info[key] = value
        setAddInfo(info)
    }
    const changeDrawer = (value) => {
        setEditDrawerVisible(value)
        if (!value) {
            setEditDrawerInfo({})
        }
    }
    const editDrawerHander = {
        getDetail: function (data, sign) {
            data.sign = sign
            data.teacherInfo = {
                UserName: data.teacherName,
                UserID: data.teacherId,
                PhotoPath: data.headshot
            }
            setEditDrawerInfo(data)
            changeDrawer(true)
        },
        setDetail: function () {
            let info = JSON.parse(JSON.stringify(editDrawerInfo))
            let teacherInfo = info.teacherInfo
            if (!teacherInfo || (!teacherInfo.userId)) {
                message.warn(`请选择${info.sign === "week" ? "值周" : "值日"}老师`)
                return
            }
            if (!info.teacherPhone) {
                message.warn(`请输入联系方式`)
                return
            }
            if (!/^[0-9|\-|/]*$/g.test(info.teacherPhone)) {
                message.warn(`联系方式格式不正确，应由数字、 -、 /组成`)
                return
            }
            let list = [], updateList = []
            if (info.sign === "week") {
                list = JSON.parse(JSON.stringify(weekList))
                list.forEach((item) => {
                    if (item.weekTypeId === editDrawerInfo.weekTypeId) {
                        updateList.push({
                            ...item,
                            teacherName: teacherInfo.userName || teacherInfo.UserName,
                            teacherId: teacherInfo.userId || teacherInfo.UserID,
                            headshot: teacherInfo.photoPath || teacherInfo.PhotoPath,
                            teacherPhone: info.teacherPhone
                        })
                    } else {
                        updateList.push(item)
                    }
                })
                setWeekList(updateList)
            } else {
                list = JSON.parse(JSON.stringify(dayList))
                list.forEach((item) => {
                    if (item.weekDay === editDrawerInfo.weekDay) {
                        updateList.push({
                            ...item,
                            teacherName: teacherInfo.userName || teacherInfo.UserName,
                            teacherId: teacherInfo.userId || teacherInfo.UserID,
                            headshot: teacherInfo.photoPath || teacherInfo.PhotoPath,
                            teacherPhone: info.teacherPhone
                        })
                    } else {
                        updateList.push(item)
                    }
                })
                setDayList(updateList)
            }
            changeDrawer(false)
        },
        editInfo: (key, value) => {
            let info = JSON.parse(JSON.stringify(editDrawerInfo))
            if (key === "teacherInfo") {
                let url = window.BasicProxy + `/api/common/user/contact/information`
                fetch
                    .get({
                        url, params: {
                            userId: value.userId || value.UserID
                        }
                    })
                    .then((res) => res.json())
                    .then((res) => {
                        if (res.code == 200) {
                            let data = res.data
                            let tel = !Array.isArray(data) ? data ? data.telephone || data.telephone2 : "" : data[0] ? data[0].telephone || data[0].telephone2 : ""
                            info[key] = value
                            info["teacherPhone"] = tel
                            setEditDrawerInfo(info)
                        }
                    })
                return
            }
            info[key] = value
            setEditDrawerInfo(info)
        }
    }
    useEffect(() => {
        if (typeof dayInfo === "object" && !editInfo.weekId) {
            let list = JSON.parse(JSON.stringify(dayInfo))
            setDayList(list)
        }
        if (Array.isArray(kindList) && !editInfo.weekId) {
            let list = kindList.map((item) => {
                return {
                    id: item.id,
                    weekType: item.weekType,
                    weekTypeId: item.weekTypeId,
                    teacherId: "",
                    teacherName: "",
                    teacherPhone: "",
                    headshot: ""
                }
            })
            setWeekList(list)
        }
        if (editInfo.weekId) {
            let info = JSON.parse(JSON.stringify(editInfo))
            info.weekGroupInfo = {
                UserName: info.weekGroupName,
                UserID: info.weekGroupId,
                PhotoPath: info.headshot
            }
            info.range = [info.weekStartTime, info.weekEndTime]
            info.dutyDayTeacherList.forEach((item) => {
                item.dayTime = item.dayTime.substr(0, 10)
                item.week = weekTextInfo[item.weekDay]
            })
            let list = []
            Array.isArray(kindList) &&
                kindList.forEach((item) => {
                    let obj = {
                        id: item.id,
                        weekType: item.weekType,
                        weekTypeId: item.weekTypeId,
                        teacherId: "",
                        teacherName: "",
                        teacherPhone: "",
                        headshot: ""
                    }
                    info.dutyWeekTeacherList.forEach((child) => {
                        if (child.weekTypeId === item.weekTypeId) {
                            obj.teacherId = child.teacherId
                            obj.teacherName = child.teacherName
                            obj.teacherPhone = child.teacherPhone
                            obj.headshot = child.headshot
                            obj.id = child.id
                        }
                    })
                    list.push(obj)
                })
            setAddInfo(info)
            setWeekList(list)
            setDayList(info.dutyDayTeacherList)
        }
    }, [dayInfo, editInfo, kindList])
    return (
        <Modal
            className={sessionStorage.getItem('skin') == 's1' ? 'add_modal' : sessionStorage.getItem('skin') == 's2' ? 'add_modal2' : 
                sessionStorage.getItem('skin') == 's3' ? 'add_modal3' : sessionStorage.getItem('skin') == 's4' ? 'add_modal4' : 
                sessionStorage.getItem('skin') == 's5' ? 'add_modal5' : 'add_modal6'
            }
            title={editInfo.weekId ? "编辑值周" : "添加值周"}
            width={740}
            height={682}
            changeVisible={changeAddModal}
            onOk={addMethod}
            noFooter={true}
            onCancel={() => changeAddModal(false)}
            visible={visible}>
            <div className="add_modal_container">
                <InfoOption
                    optionName="值周名称"
                    className="marginTop"
                    type="input"
                    width={540}
                    maxLength={50}
                    optional={true}
                    getVal={(value) => editAddInfo("weekName", value)}
                    value={addInfo.weekName} />
                <InfoOption
                    className="block myDateRange"
                    optionName="日期范围"
                    width={240}
                    type="dateRange"
                    optional={true}
                    min={currentTermInfo.startDate}
                    max={currentTermInfo.endDate}
                    getVal={(value) => editAddInfo("range", value)}
                    value={addInfo.range} />
                <div>
                    <InfoOption
                        optionName="设置值周组长"
                        type="search"
                        width={240}
                        optional={true}
                        userType="0,1,11"
                        getVal={(value) => editAddInfo("weekGroupInfo", value)}
                        value={addInfo.weekGroupInfo} />
                    <InfoOption
                        className="tel"
                        optionName="联系方式"
                        type="input"
                        maxLength={11}
                        optional={true}
                        width={201}
                        getVal={(value) => editAddInfo("weekGroupPhone", value)}
                        value={addInfo.weekGroupPhone} />
                </div>
                <div className="info_option">
                    <span className="option_name">值周安排:</span>
                    {
                        weekList.length > 0 ?
                            <div className="list-table" style={{ width: "540px" }}>
                                <div className="table-thead">
                                    <div className="table-th" style={{ width: "30%" }}>值周类型</div>
                                    <div className="table-th" style={{ width: "43%" }}>值周老师</div>
                                    <div className="table-th" style={{ width: "27%" }}>操作</div>
                                </div>
                                {
                                    weekList.length > 0 ?
                                        weekList.map((item, index) => (
                                            <div className="table-tr" key={index}>
                                                <div className="table-td" style={{ width: "30%", fontSize: "12px" }}>{item.weekType}</div>
                                                <div className="table-td" style={{ width: "43%" }}
                                                    title={item.teacherName ? item.teacherName + `(${item.teacherPhone})` : "暂未设置"}>
                                                    {
                                                        item.teacherName ?
                                                            <span>{item.teacherName}<span style={{ color: "#999", marginLeft: 3 }}>({item.teacherPhone})</span></span> :
                                                            <span style={{ color: "#999" }}>暂未设置</span>
                                                    }
                                                </div>
                                                <div className="table-td" style={{ width: "27%" }}>
                                                    <span className="operate_btn" onClick={() => editDrawerHander.getDetail(item, "week")}>编辑</span>
                                                </div>
                                            </div>
                                        )) :
                                        <Empty
                                            // className={"list-empty"}
                                            style={{ margin: "100px 0" }}
                                            title={"暂无内容~"}
                                            type={"3"}
                                        ></Empty>
                                }
                            </div> :
                            <span className="empty_text" onClick={() => changeKindModal(true)}>前往添加值周类型</span>
                    }
                </div>
                <div className="info_option">
                    <span className="option_name">值日人员安排:</span>
                    <div className="list-table" style={{ width: "540px" }}>
                        <div className="table-thead">
                            <div className="table-th" style={{ width: "30%" }}>时间</div>
                            <div className="table-th" style={{ width: "43%" }}>值日老师</div>
                            <div className="table-th" style={{ width: "27%" }}>操作</div>
                        </div>
                        {
                            dayList.length > 0 ?
                                dayList.map((item, index) => (
                                    <div className="table-tr" key={index}>
                                        <div className="table-td" style={{ width: "30%", fontSize: "12px" }}>
                                            {item.week}
                                            {
                                                item.dayTime ?
                                                    <span style={{ color: "#999" }}>({item.dayTime})</span> :
                                                    ""
                                            }
                                        </div>
                                        <div className="table-td" style={{ width: "43%" }}
                                            title={item.teacherName ? `${item.teacherName}(${item.teacherPhone})` : "暂未设置"}>
                                            {
                                                item.teacherName ?
                                                    <span>{item.teacherName}<span style={{ color: "#999", marginLeft: 3 }}>({item.teacherPhone})</span></span> :
                                                    <span style={{ color: "#999" }}>暂未设置</span>
                                            }
                                        </div>
                                        <div className="table-td" style={{ width: "27%" }}>
                                            <span className="operate_btn" onClick={() => editDrawerHander.getDetail(item, "day")}>编辑</span>
                                        </div>
                                    </div>
                                )) :
                                <Empty
                                    // className={"list-empty"}
                                    style={{ margin: "100px 0" }}
                                    title={"暂无内容~"}
                                    type={"3"}
                                ></Empty>
                        }
                    </div>
                </div>
            </div>
            <div className="modal_footer">
                <div className="confirm_btn" onClick={addMethod}>确定</div>
                <div className="cancel_btn" onClick={() => changeAddModal(false)}>取消</div>
            </div>
            <Drawer
                title={
                    <p className="drawer_title">编辑1<i className="closelogo" onClick={() => changeDrawer(false)}></i></p>
                }
                width={422}
                placement="right"
                className="day_edit_drawer"
                visible={editDrawerVisible}
                closable={false}
                maskStyle={{ opacity: 0.5, animation: "none" }}
                getContainer={false}
                style={{ position: 'absolute' }}
                onClose={() => changeDrawer(false)}>
                <InfoOption
                    optionName={`${editDrawerInfo.sign === "week" ? "值周" : "值日"}老师`}
                    type="search"
                    width={240}
                    optional={true}
                    userType="0,1,11"
                    getVal={(value) => editDrawerHander.editInfo("teacherInfo", value)}
                    value={editDrawerInfo.teacherInfo} />
                <InfoOption
                    optionName="联系方式"
                    type="input"
                    maxLength={11}
                    width={200}
                    optional={true}
                    getVal={(value) => editDrawerHander.editInfo("teacherPhone", value)}
                    value={editDrawerInfo.teacherPhone} />
                <div className="regular_footer">
                    <div className="ok_btn" onClick={editDrawerHander.setDetail}>确定</div>
                    <div className="no_btn" onClick={() => changeDrawer(false)}>取消</div>
                </div>
            </Drawer>
        </Modal>
    )
}

export default AddModal